<!-- 班级管理 -->

<template>
  <div>
    <!-- 功能 -->
    <div class="header-menu" style="display: flex;">
      <el-select
          style="width: 60%;"
          v-model="value1"
          placeholder="年级"
          @change="queryClassByGrade"
          clearable
      >
        <el-option
            v-for="item in gradeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        ></el-option>
      </el-select>
      <el-button style="width: 8%;" type="primary" @click="addClass()">
        新增班级
      </el-button>
    </div>

    <el-table :data="classInfoData" size="mini" stripe highlight-current-row>
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="gradeName" label="年级"></el-table-column>
      <el-table-column prop="classNo" label="班级编号"></el-table-column>
      <el-table-column prop="className" label="班级名称"></el-table-column>
      <el-table-column prop="realname" label="班主任"></el-table-column>
      <el-table-column prop="num" label="学生人数"></el-table-column>

      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="danger" size="mini" @click="deleteById(scope.row)">删除</el-button>
          <el-button type="primary" size="mini" @click="editById(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加班级 -->
    <el-dialog v-model="visibleAdd" title="班级">
      <el-form :model="addClassData" ref="addClassDataRef" :rules="formRules" label-position="left" label-width="80px">
        <el-form-item label="年级" prop="gradeNo">
          <el-select v-model="addClassData.gradeNo" placeholder="请选择年级" clearable>
            <el-option
                v-for="item in gradeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 选择班主任 -->
        <el-form-item label="班主任" prop="id">
          <el-select v-model="addClassData.id" placeholder="请选择班主任" clearable>
            <el-option
                v-for="item in teacherOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级编号" prop="classNo">
          <el-input v-model="addClassData.classNo" placeholder="请输入班级编号"/>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="addClassData.className" placeholder="请输入班级名称"/>
        </el-form-item>
        <el-form-item label="学生人数" prop="num">
          <el-input v-model="addClassData.num" placeholder="请输入学生人数" type="number"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visibleAdd = false">取消</el-button>
        <el-button type="primary" @click="commitAddClass">提交</el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="footer-button">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          background
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance, reactive} from 'vue';

const {proxy} = getCurrentInstance();

const classInfoData = ref([]);
const addClassData = ref({
  gradeNo: '',
  num: '',
  id: '',
});
const checkIfNumber = (rule, value, callback) => {
  if (value && isNaN(value)) {
    callback(new Error('学生人数必须为数字'));
  } else {
    callback(); // 验证通过
  }
};
// 校验规则
const formRules = reactive({
  gradeNo: [{required: true, message: '请选择年级', trigger: 'change'}],
  id: [{required: true, message: '请选择班主任', trigger: 'change'}],
  classNo: [
    {required: true, message: '班级编号不能为空', trigger: 'blur'},
    {pattern: /^[A-Za-z0-9]+$/, message: '班级编号只能包含字母和数字', trigger: 'blur'}
  ],
  className: [{required: true, message: '班级名称不能为空', trigger: 'blur'}],
  num: [
    {required: true, message: '学生人数不能为空', trigger: 'blur'},
    {validator: checkIfNumber, message: '学生人数必须为数字', trigger: 'blur'},
    {min: 1, message: '学生人数必须大于0', trigger: 'blur'}
  ]
});

const visibleAdd = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const value1 = ref('');
const gradeOptions = ref([
  {value: '01', label: '高一'},
  {value: '02', label: '高二'},
  {value: '03', label: '高三'},
]);
const teacherOptions = ref([]);

onMounted(() => {
  allClassInfo();
});


const validateForm = () => {
  return new Promise((resolve) => {
    proxy.$refs.addClassDataRef.validate((valid) => {
      resolve(valid);
    });
  });
};
const commitAddClass = async () => {
  const valid = await validateForm();

  if (!valid) {
    ElMessage.error('请输入对应参数');
    return
  }
  if (addClassData.value.cid == '' || addClassData.value.cid == undefined) {
    await proxy.$api.addClassinfo(addClassData.value);
    allClassInfo();
    ElMessage({
      message: '添加班级成功',
      type: 'success',
    });
    visibleAdd.value = false;
    addClassData.value = {
      gradeNo: '',
      num: '',
      cid: '',
    }
  } else {
    modifyClassinfo(addClassData.cid, addClassData.value)
  }
};

const addClass = () => {
  allTeacher();
  visibleAdd.value = true;
  addClassData.value = {}
};

const allTeacher = async () => {
  const result = await proxy.$api.allTeacher();
  teacherOptions.value = result.map((v) => ({
    value: v.id,
    label: v.realname,
  }));
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  allClassInfo();
};

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  allClassInfo();
};

const queryClassByGrade = () => {
  allClassInfo(value1.value);
};

const allClassInfo = async (gradeNo = '') => {
  const result = await proxy.$api.queryClassInfos(page.value, gradeNo);
  classInfoData.value = result.records;
  total.value = result.total;
};

const deleteById = async (row) => {
  deleteClassinfoById(row.id);
};

const editById = async (row) => {
  visibleAdd.value = true;
  allTeacher();
  console.log(row,Number(row.num))
  addClassData.value.cid = row.id;
  addClassData.value.gradeNo = gradeOptions.value.find(item => item.label === row.gradeName).value;
  addClassData.value.id = teacherOptions.value.find(item => item.label === row.realname)?.value;
  addClassData.value.classNo = row.classNo;
  addClassData.value.className = row.className;
  addClassData.value.num = ""+row.num;
};

// 根据id删除教材信息
const deleteClassinfoById = async (id) => {
  await proxy.$api.deleteClassinfoById(id);
  allClassInfo();
  ElMessage({message: '删除成功', type: 'success'});
}

const modifyClassinfo = async () => {
  await proxy.$api.modifyClassinfo(addClassData.value.cid, addClassData.value);
  allClassInfo();
  ElMessage({
    message: '更新班级信息成功',
    type: 'success',
  });
  visibleAdd.value = false;
  addClassData.value = {
    gradeNo: '',
    num: '',
    cid: '',
  }
}
</script>

<style lang="less" scoped>
.footer-button {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.header-menu {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 0;
  text-align: left;
}
</style>
